package com.binguo.wxapi.service;

import com.binguo.common.util.ImageBase64Util;
import com.binguo.common.util.ImageUtil;
import com.binguo.common.util.JsonUtil;
import com.binguo.common.util.LoggerUtil;
import com.binguo.model.mapper.LogProductImgMapper;
import com.binguo.model.mapper.ProductMapper;
import com.binguo.model.mapper.RecipMapper;
import com.binguo.model.mapper.ShopMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.ProductYpTypeRepository;
import com.binguo.service.ShopProductMsgService;
import com.binguo.wxapi.baidu.BaiduRecUtil;
import com.binguo.yprecapi.YpRecService;
import com.binguo.yprecapi.model.ImgRecResult;
import com.binguo.yprecapi.model.Results;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
public class BowlService implements InitializingBean {
    private static Logger logger = LoggerFactory.getLogger(BowlService.class);

    public HttpHeaders DEFAULT_JSON_HEADER;

    public HttpHeaders DEFAULT_JSON_HEADER_UTF8;
    public RestTemplate restTemplate = new RestTemplate();

    @Resource
    private ProductYpTypeRepository productYpTypeRepository;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private YpRecService ypRecService;

    @Resource
    private RecipMapper recipMapper;

    @Resource
    private BaiduRecUtil baiduRecUtil;

    @Resource
    private LogProductImgMapper logProductImgMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ShopProductMsgService shopProductMsgService;

    public String localRecIp;
    public String productYPRecIpAddress;

    private String bowlRecUrl;

    public String wxapiFilepath = "/usr/local/nginx/html";


    private static String ipAddress = System.getenv("ipAddress");


    public Boolean checkBowlLocation(Integer shopId, Integer productId, Integer branchId, String filepath){
        long localrecStart = System.currentTimeMillis();

        HttpHeaders DEFAULT_JSON_HEADER = new HttpHeaders();
        MediaType jsontype = MediaType.APPLICATION_JSON;
        DEFAULT_JSON_HEADER.setContentType(jsontype);
        String localFilepath = wxapiFilepath + "/wxapiimg/" + shopId;


        File file = new File(localFilepath);

        if (!file.exists()) {
            file.mkdir();
        }

        localFilepath += "/" + productId;

        file = new File(localFilepath);

        if (!file.exists()) {
            file.mkdir();
        }

        localFilepath += "/temp";

        file = new File(localFilepath);

        if (!file.exists()) {
            file.mkdir();
        }

        String tempPath = localFilepath + "/" + shopId + "_" + productId + "_" + UUID.randomUUID();

        localFilepath = tempPath + ".png";

        ImageBase64Util.downloadNetImage(filepath, localFilepath);

        String localFilepathUrl = localFilepath.replace(wxapiFilepath, "http://" + ipAddress);

        Map<String, String> param = new HashMap<>();
        param.put("imgUrl", localFilepathUrl);
        param.put("shopId", shopId + "");

        try {
            String jsonParam = JsonUtil.toJson(param);

            HttpEntity entity = new HttpEntity<>(jsonParam, DEFAULT_JSON_HEADER);


            logger.info("图片检测,local DataLoadService.bowlRecUrl：{}, param:{}", bowlRecUrl, jsonParam);


            ResponseEntity<String> recImgResult = new RestTemplate().postForEntity(bowlRecUrl, entity, String.class);
            String resultStr = recImgResult.getBody();

            logger.info("碗识别结果：{}", resultStr);
            if (resultStr == null) {
                logger.info("碗模型识别无结果=");
                return false;
            }
            resultStr = resultStr.substring(resultStr.indexOf("results")-2);
            ImgRecResult resResult = JsonUtil.parse(resultStr, ImgRecResult.class);


            logger.info("resResult.getNumber()=", resResult.getNumber());

            if (resResult.getNumber() > 0) {
                if (resResult.getNumber() > 1) {
                    return false;
                }

                Results res = resResult.getResults().get(0);
                if (res.getScore() < 0.5) {
                    return false;
                }
                int left = res.getLocation().getLeft();
                int top = res.getLocation().getTop();

                int width = res.getLocation().getWidth();
                int height = res.getLocation().getHeight();

                String cutImgPath = tempPath + "cut.png";

                int cut = 10;
                ImageUtil.cutImageWithResize(localFilepath, cutImgPath, left + cut,top + cut, width - cut, height - cut, 401);
                LogProductImg logProductImg = new LogProductImg();

                Shop shop = shopMapper.selectByPrimaryKey(shopId);
                String cont_sign = null;
                logProductImg.setImgCutNetUrl(cutImgPath.replace(wxapiFilepath, "http://" + ipAddress));
                logProductImg.setCutImg(cutImgPath);
                logProductImg.setProductId(productId);
                logProductImg.setShopId(shopId);
                logProductImg.setSourceImg(filepath);

                logProductImg.setCreateTime(new Date());
                logProductImg.setBaiduDeleted(0);
                logProductImg.setFromWxUpload(1);
                logProductImg.setBranchId(branchId);

                if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 4) {
                    LoggerUtil.console.info("ypRecService.addImg, filepath:{},shopId:{},localIp:{}"
                            ,logProductImg.getImgCutNetUrl(),branchId,localRecIp );
                    ypRecService.addImg(logProductImg.getImgCutNetUrl(), branchId, productId, localRecIp);//分店级
                }else if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 5) {
                    LoggerUtil.console.info("ypRecService.addImg, filepath:{},shopId:{},localIp:{}"
                            ,logProductImg.getImgCutNetUrl(),branchId,localRecIp );
                    ypRecService.addImg(logProductImg.getImgCutNetUrl(), branchId, productId,productYPRecIpAddress + ":5001");//分店级
                }else if (shop.getProductRecType() != null && shop.getProductRecType().intValue() == 6) {
                    LoggerUtil.console.info("shopProductMsgService.addImg, filepath:{},shopId:{},localIp:{}"
                            ,logProductImg.getImgCutNetUrl(),branchId,localRecIp );
                    shopProductMsgService.addInsertProductImgMessage(logProductImg);

                }else {
                    cont_sign = baiduRecUtil.addImg(shopId, branchId, cutImgPath, shopId + "_" + productId);
                    logProductImg.setContSign(cont_sign);
                }



                logProductImgMapper.insert(logProductImg);

                Product product = new Product();
                product.setProductpic(filepath);
                product.setId(productId);
                productMapper.updateByPrimaryKeySelective(product);


                long endTime = System.currentTimeMillis();
                logger.info("碗识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));
                logger.info("碗识别结果=" + JsonUtil.toJson(res));


                return true;
            }else {
                long endTime = System.currentTimeMillis();
                logger.info("本地模型识别无结果");
                logger.info("本地模型识别完成=" + endTime + ",huawei rec intelval=" + (endTime - localrecStart));
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("碗识别错误：{}", e.getMessage());
            return false;
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
        Condition productYpTypeCondition = new Condition(ProductYpType.class);
        productYpTypeCondition.or().andEqualTo("ypType", 1);
        List<ProductYpType> productYpTypeList = productYpTypeRepository.findByCondition(productYpTypeCondition);
        if (productYpTypeList != null && productYpTypeList.size() > 0) {
            bowlRecUrl = productYpTypeList.get(0).getRecUrl();
        }

        List<Recip> recipList = recipMapper.selectAll();
        if (recipList != null && recipList.size() > 0) {
            localRecIp = recipList.get(0).getAddress();

            for (Recip recip : recipList) {
                if (recip.getIpType() != null && recip.getIpType().intValue() == 1) {
                    productYPRecIpAddress = recip.getAddress();
                    break;
                }
            }
        }



        File file = new File(wxapiFilepath);

        if (!file.exists()) {
            file.mkdir();
        }

        file = new File(wxapiFilepath + "/wxapiimg");

        if (!file.exists()) {
            file.mkdir();
        }
    }
}
